package com.tz.fruit.dao.impl;

import com.tz.fruit.dao.IUserDao;
import com.tz.fruit.entity.User;


import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


import javax.transaction.Transactional;
import java.util.List;


/**
 * Created by Administrator on 2017/7/20.
 */
@Repository
public class UserDaoImpl implements IUserDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession() {
        //1.可以将session和当前的线程进行绑定,并且不需要用户进行手动关闭.
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void save(User u) {
        getSession().save(u);
    }

    @Override
    public User findByUsername(String username) {
        return (User) getSession().createQuery("from User where username=:uname")
                .setParameter("uname", username).uniqueResult();
    }

    @Override
    public void updateStatus(String username) {
        getSession().createQuery("update User set status=status+1 where username=:uname")
                .setParameter("uname", username).executeUpdate();
    }


    @Override
    public List<User> findAll(String username, Long pageNow, Long pageSize) {
        Criteria c = getSession().createCriteria(User.class, "u");
        //判断条件是否存在.
        if (null != username && username.trim().length() > 0) {
            c.add(Restrictions.like("u.username", "%" + username + "%"));
        }
        c.setFirstResult((int) ((pageNow - 1) * pageSize)).setMaxResults(pageSize.intValue());

        return c.list();

    }

    @Override
    public long findRowCount(String username) {
        Criteria c = getSession().createCriteria(User.class, "u");
        //判断条件是否存在.
        if (null != username && username.trim().length() > 0) {
            c.add(Restrictions.like("u.username", "%" + username + "%"));
        }
        return (long) c.setProjection(Projections.rowCount()).uniqueResult();
    }

    @Override
    public void update(User user) {
        getSession().update(user);
    }

}
